package edu.fdzc.learn.controller;


import edu.fdzc.learn.common.Result;
import edu.fdzc.learn.entity.User;
import edu.fdzc.learn.mapper.UserMapper;
import edu.fdzc.learn.service.UserService;
import edu.fdzc.learn.utils.JwtUtil;
import edu.fdzc.learn.utils.Md5Util;
import edu.fdzc.learn.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping()
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;

    @PostMapping("/auth/register")
    public Result register(String username,String password,String role){

        //查询用户
        User u = userService.findByUserName(username);
        if(u == null){
            userService.register(username,password,role);
            return Result.success();
        }

        return Result.error("用户名已经被占用");
    }

    @PostMapping("/auth/login")
    public Result<String> login(String username,String password){
        //根据用户名擦汗寻用户
        User u = userService.findByUserName(username);
        if(u == null){
            return Result.error("账户未注册");
        }
        //判断密码
        if(Md5Util.getMD5String(password).equals(u.getPassword())){
            Map<String , Object> claims = new HashMap<>();
            claims.put("id",u.getId());
            claims.put("role",u.getRole());
            String thoken = JwtUtil.genToken(claims);
            return Result.success(thoken);
        }
        return Result.error("密码错误");
    }

    @GetMapping("/user/profile")
    public Result<User> userInfo(){
        Map<String,Object> map = ThreadLocalUtil.get();
        int id = (int) map.get("id");
        User u = userService.findById(id);
        return Result.success(u);
    }

    @PutMapping("/user/profile")
    public Result update(@RequestBody User user){
        Map<String,Object> map = ThreadLocalUtil.get();
        int id = (int) map.get("id");
        user.setId(id);
        userService.update(user);
        return Result.success("更新成功");
    }

    @PatchMapping("/user/updateAvatwer")
    public Result updateAvatwer(@RequestParam String avatwer){
        Map<String,Object> map = ThreadLocalUtil.get();
        int id = (int) map.get("id");
        User u = new User();
        u.setId(id);
        userService.update(u);
        return Result.success();
    }


}
